package cn.buk.tms.flight.service;

import cn.buk.tms.entity.misc.EntDepartment;
import cn.buk.tms.entity.order.flight.FlightRefundOrder;
import cn.buk.qms.service.BaseFlightOrderService;
import cn.buk.qms.service.FlightRefundOrderService;
import cn.buk.common.util.DateUtil;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

import static cn.buk.common.JsonResult.STATUS_OK;
import static cn.buk.tms.common.constant.TmsConstant.FLIGHT_AUTO_TICKETING_NDC_CZ;

/**
 * @author yfdai
 */
@Service
public class AutoRefundServiceImpl extends BaseFlightOrderService implements AutoRefundService {

  public static final Logger logger = LogManager.getLogger(AutoRefundServiceImpl.class);

  @Autowired
  private FlightRefundOrderService refundOrderService;

  @Override
  public void checkFlightRefundOrder(final int enterpriseId, final String username) {
    //搜索退票单
    final Date startDate = DateUtil.addDays(DateUtil.getCurDate(), -10);
    var refundOrders = refundOrderDao.searchWaiting(enterpriseId, startDate);

    if (refundOrders.isEmpty()) {
      return;
    }

    logger.info("waiting for refund: {}", refundOrders.size());

    for (var refundOrder : refundOrders) {
      if (refundOrder.getSupplier() == null) {
        continue;
      }

      if (refundOrder.getSupplier().getIsBsp() != FLIGHT_AUTO_TICKETING_NDC_CZ) {
        continue;
      }

      if (refundOrder.getCustomer() != null && refundOrder.getCustomer().getTestMode() == 1) {
        //测试模式的客户，不自动退票
        continue;
      }

      int retCode = execAutoRefundOrder(enterpriseId, username, refundOrder);
      logger.info("{}: {}.", refundOrder.getRefundOrderNo(), retCode);
    }
  }

  /**
   * @return 错误代码：0 - 没有错误；
   * 其它数字 - 错误信息的代码
   */
  private int execAutoRefundOrder(final int enterpriseId, final String username, final FlightRefundOrder refundOrder) {
    //1. 是否已认领
    //1.1 未认领，则认领，并判断航司退票费是否准确; 不准确，并发出提醒消息
    //1.2 已认领，判断是否为当前用户，不是，则不处理
    if (StringUtils.isBlank(refundOrder.getTicketer())) {
      //准备认领后处理
      int retCode = refundOrderDao.processFlightRefund(enterpriseId, username, refundOrder.getId());
      if (retCode != 1) {
        doSendAlert(enterpriseId, "退票单" + refundOrder.getRefundOrderNo() + "认领失败 by " + username, "Dai", 0);
        return 1;
      }

      //TODO 校验航司退票费是否相符 yfdai 2021-09-30
    } else if (!username.equalsIgnoreCase(refundOrder.getTicketer())) {
      return 2;
    }

    if (StringUtils.isBlank(refundOrder.getExternalOrderNo())) {
      var jr = refundOrderService.createNdcOrderRefund(enterpriseId, username, refundOrder.getId());
      if (STATUS_OK.equalsIgnoreCase(jr.getStatus())) {
        //向ndc提交退票成功，要在本地修改退票单状态为 “已提交”  yfdai 2021-10-18
        refundOrderDao.submitFlightRefund(enterpriseId, username, refundOrder.getId());
        return 0;
      } else {
        String content = String.format("退票单(%s)向航司提交失败，反馈信息：%s", refundOrder.getRefundOrderNo(), jr.getErrmsg());
        doSendAlert(enterpriseId, content, null, EntDepartment.DEPT_TICKETING);
        return 1;
      }
    } else {
      //同步退票单状态
      refundOrderService.syncNdcOrderRefundInfo(enterpriseId, username, refundOrder.getId());
    }

    return 0;
  }
}
